package com.lenovo.smarttraffic.ui.fragment.DataAnalysisFragment;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.google.gson.Gson;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.bean.DataAnalysis.AllCarMessageInfo;
import com.lenovo.smarttraffic.bean.DataAnalysis.ErrorCarMessageInfo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class FiveFragment extends Fragment {


    private View view;
    private AllCarMessageInfo allInfo;
    private List<ErrorCarMessageInfo.ROWS_DETAIL> errorList;
    private List<AllCarMessageInfo.ROWS_DETAIL> allList;
    private WebView webView;

    public FiveFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_five, container, false);
        //初始化WebView
        webView = view.findViewById(R.id.data_analysis_webview5);
        webView.loadUrl("file:///android_asset/DataAnalysis/FiveFragment.html");
        webView.setWebViewClient(new WebViewClient());
        webView.getSettings().setJavaScriptEnabled(true);
        //请求数据
        sendAllCarData();
        return view;
    }

    //获取所有车辆的信息
    public void sendAllCarData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = RequestBody.create(MediaType.parse("app/json"),
                            "{\"UserName\":\"user1\"}");
                    Request request = new Request.Builder()
                            .url("http://192.168.1.102:8088/transportservice/action/GetCarInfo.do")
                            .post(requestBody)
                            .build();
                    Response response = client.newCall(request).execute();
                    String parseData = response.body().string();
                    //数据解析
                    parseAllCarData(parseData);
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    public void parseAllCarData(String jsonData) {
        Gson gson = new Gson();
        allInfo = gson.fromJson(jsonData, AllCarMessageInfo.class);
        allList = new ArrayList<>();
        allList.addAll(allInfo.getROWS_DETAIL());
        //获取违章车辆信息
        sendErrorCarData();
    }

    //获取违章车辆的信息
    public void sendErrorCarData() {
        try {
            OkHttpClient client = new OkHttpClient();
            RequestBody requestBody = RequestBody.create(MediaType.parse("app/json"),
                    "{\"UserName\":\"user1\"}");
            Request request = new Request.Builder()
                    .url("http://192.168.1.102:8088/transportservice/action/GetAllCarPeccancy.do")
                    .post(requestBody)
                    .build();
            Response response = client.newCall(request).execute();
            String parseData = response.body().string();
            //数据解析
            parseErrorCarData(parseData);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void parseErrorCarData(String jsonData) {
        Gson gson = new Gson();
        ErrorCarMessageInfo errorInfo = gson.fromJson(jsonData, ErrorCarMessageInfo.class);
        errorList = new ArrayList<>();
        errorList.addAll(errorInfo.getROWS_DETAIL());
        //给有违章的集合去重
        for (int i = 0; i < errorList.size() - 1; i++) {
            for (int j = i + 1; j < errorList.size(); j++) {
                if ((errorList.get(i).getCarnumber()).equals(errorList.get(j).getCarnumber())) {
                    errorList.remove(j);
                    j--;
                }
            }
        }
        //统计违章者的性别
        int[] errorData = new int[]{0, 0};
        for (int i = 0; i < errorList.size(); i++) {
            for (int j = 0; j < allList.size(); j++) {
                if ((errorList.get(i).getCarnumber()).equals(allList.get(j).getCarnumber())) {
                    char cardId = allList.get(j).getPcardid().charAt(16);
                    if ((Integer.parseInt(cardId+"")) % 2 == 1) {
                        errorData[0]++;
                    } else {
                        errorData[1]++;
                    }
                }
            }
        }

        //遍历所有的违章和所有的信息，删除所有的违章信息，剩下的为未违章的车辆
        for (int i = 0; i < errorList.size(); i++) {
            for (int j = 0; j < allList.size(); j++) {
                if ((errorList.get(i).getCarnumber()).equals(allList.get(j).getCarnumber())) {
                    allList.remove(j);
                    j--;
                }
            }
        }
        //统计未违章车主的性别
        int[] noErrorData = new int[]{0, 0};
        for (int i = 0; i < allList.size(); i++) {
            char cardId = allList.get(i).getPcardid().charAt(16);
            if ((Integer.parseInt(cardId+"")) % 2 == 1) {
                noErrorData[0]++;
            } else {
                noErrorData[1]++;
            }
        }

        //向WebView传递两个数组
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webView.loadUrl("javascript:getData(\""+ Arrays.toString(errorData) +"\", \""+Arrays.toString(noErrorData)+"\")");
            }
        });
    }

}
